package com.kehutong.admin.service;

import com.kehutong.admin.entity.SystemTag;
import com.kehutong.common.entity.Root;
import org.apache.http.message.BasicNameValuePair;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindArray;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.IDGenerate;
import org.coraframework.util.Objects;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 系统标签服务类
 *
 * @author: liukunlong
 * @date: 2021-07-28 10:08
 */
@WebService("/admin/sys/tag/service")
public class SystemTagService {

    static final Logger logger = LoggerFactory.getLogger(SystemTagService.class);


    @Inject
    private JdbcSession jdbcSession;


    /**
     * 获取所有标签,重置标签有用到
     *
     * @param jsonObject 查询对象
     * @return 标签列表
     * @throws IOException 操作异常
     */
    @ReqMapping("/all")
    public List<SystemTag> all(JSONObject jsonObject) throws Exception {
        List<SystemTag> result = null;
        FindArray<SystemTag> find = jdbcSession.findArray(SystemTag.class)
                .eq(jsonObject, "id", "pid")
                .like(jsonObject, "name")
                .eq("deleted", false)
                .order("sort", "desc");
        result = find.exe();
        if (logger.isDebugEnabled()) {
            logger.debug("result:" + result);
        }
        return result;
    }


    /**
     * 根据条件获取标签列表
     *
     * @param jsonObject 查询对象
     * @return 标签列表
     * @throws IOException 操作异常
     */
    @ReqMapping("/page")
    public Page<SystemTag> page(JSONObject jsonObject) throws Exception {
        String tagName = jsonObject.getString("tagName");

        Page<SystemTag> result = null;
        FindPage<SystemTag> findPage = jdbcSession.findPage(SystemTag.class)
                .eq(jsonObject, "id", "pid")
                .like(jsonObject, "name")
                .eq("group", false)
                .eq("deleted", false)
                .order("sort", "desc")
                .page(jsonObject);
        result = findPage.exe();
        if (logger.isDebugEnabled()) {
            logger.debug("result:" + result);
        }
        if (Objects.nonNull(result)) {
            List<SystemTag> systemTagList = result.getList();
            for (SystemTag systemTag : systemTagList) {
                SystemTag systemTagGroup = jdbcSession.findById(SystemTag.class, systemTag.getPid());
                if (Objects.nonNull(systemTagGroup)) {
                    systemTag.setPname(systemTagGroup.getName());
                } else {
                    systemTag.setPname("");
                }
            }
        }
        return result;
    }

    /**
     * 获取标签列表
     *
     * @param jsonObject 查询对象
     * @return
     * @throws Exception
     */
    @ReqMapping("/list")
    public Object list(JSONObject jsonObject) throws Exception {
        jsonObject.put("pageNo", 1);
        jsonObject.put("pageSize", Short.MAX_VALUE);
        Page<SystemTag> page = page(jsonObject);
        return page.getList();
    }

    /**
     * 获取标签内容
     *
     * @param systemTag 标签对象
     * @return
     */
    @ReqMapping("/get")
    public Object get(SystemTag systemTag) {
        return systemTag;
    }

    /**
     * 保存标签
     *
     * @param systemTag 系统标签对象
     * @return
     */
    @Bean(newInstance = true, copy = true)
    @ReqMapping("/save")
    public Object save(SystemTag systemTag) {
        String id = systemTag.getId();
        SystemTag dbSystemTag = jdbcSession.findOne(SystemTag.class)
                .eq("deleted", false)
                .eq("group", false)
                .markBegin()
                .eq("id", id).or()
                .eq("name", systemTag.getName()).or()
                .markEnd().exe();
        if (Objects.isNull(dbSystemTag)) {
            systemTag.setGroup(false);
            systemTag.setSort(System.currentTimeMillis());
            systemTag.setCreateBy(Root.ROOT_ID);
            systemTag.setCreateName("系统");
            jdbcSession.insert(systemTag);
        } else {
            dbSystemTag.setName(systemTag.getName());
            systemTag.setCreateBy(Root.ROOT_ID);
            systemTag.setCreateName("系统");
            jdbcSession.updateById(dbSystemTag);
        }
        return Result.success();
    }

    /**
     * 更新标签组及标签
     *
     * @param systemTag 系统标签对象
     * @return
     * @throws Exception
     */
    @Bean(copy = true)
    @ReqMapping("/update")
    public Object update(SystemTag systemTag) throws Exception {
        String id = systemTag.getId();
        SystemTag dbSystemTag = jdbcSession.findOne(SystemTag.class)
                .eq("group", false)
                .eq("deleted", false)
                .eq("id",id).exe();
        if (Objects.isNull(dbSystemTag)) {
            return Result.success("0", "标签不存在");
        }
        jdbcSession.updateById(systemTag);
        return Result.success();
    }


    /**
     * 删除标签
     *
     * @param systemTag 标签对象
     * @return
     */
    @ReqMapping("/delete")
    public Object delete(SystemTag systemTag) {
        systemTag.setDeleted(true);
        jdbcSession.updateById(systemTag);
        return Result.success();
    }

    /**
     * 根据条件获取标签组分页列表
     *
     * @param jsonObject 查询对象
     * @return 住户汽车列表
     * @throws IOException 操作异常
     */
    @ReqMapping("/group/page")
    public Page<SystemTag> groupPage(JSONObject jsonObject) throws Exception {
        String tagName = jsonObject.getString("tagName");

        Page<SystemTag> result = null;
        FindPage<SystemTag> findPage = jdbcSession.findPage(SystemTag.class)
                .eq(jsonObject, "id")
                .like(jsonObject, "name")
                .eq("group", true)
                .eq("deleted", false)
                .order("sort", "desc")
                .page(jsonObject);
        if (Objects.nonEmpty(tagName)) {
            List<SystemTag> systemTagList = jdbcSession.findArray(SystemTag.class)
                    .eq("group", false)
                    .eq("deleted", false)
                    .like("name", tagName).exe();
            List<String> ids = systemTagList.stream().map(SystemTag::getPid).collect(Collectors.toList());
            if (Objects.nonEmpty(ids)) {
                findPage.in("id", ids);
            }
        }
        result = findPage.exe();
        if (logger.isDebugEnabled()) {
            logger.debug("result:" + result);
        }
        if (Objects.nonNull(result)) {
            List<SystemTag> systemTagGroupList = result.getList();
            for (SystemTag systemGroupTag : systemTagGroupList) {
                List<SystemTag> systemTagList = jdbcSession.findArray(SystemTag.class)
                        .eq("pid", systemGroupTag.getId())
                        .eq("group", false)
                        .eq("deleted", false)
                        .order("sort", "desc")
                        .exe();
                systemGroupTag.setChildList(systemTagList);

            }
        }
        return result;
    }

    /**
     * 根据条件获取标签组列表
     *
     * @param jsonObject 查询对象
     * @return
     * @throws Exception
     */
    @ReqMapping("/group/list")
    public Object groupList(JSONObject jsonObject) throws Exception {
        jsonObject.put("pageNo", 1);
        jsonObject.put("pageSize", Short.MAX_VALUE);
        Page<SystemTag> page = groupPage(jsonObject);
        return page.getList();
    }

    /**
     * 获取标签组
     *
     * @param systemTagGroup 系统标签对象
     * @return
     */
    @ReqMapping("/group/get")
    public Object groupGet(SystemTag systemTagGroup) {
        if (Objects.nonNull(systemTagGroup)) {
            List<SystemTag> systemTagList = jdbcSession.findArray(SystemTag.class)
                    .eq("pid", systemTagGroup.getId())
                    .eq("group", false)
                    .eq("deleted", false)
                    .order("sort", "desc")
                    .exe();
            systemTagGroup.setChildList(systemTagList);

        }
        return systemTagGroup;
    }

    /**
     * 保存标气标签组及标签
     *
     * @param systemTagGroup 系统标签对象
     * @return
     */
    @Bean(newInstance = true, copy = true)
    @ReqMapping("/group/save")
    public Object groupSave(SystemTag systemTagGroup) {
        String id = systemTagGroup.getId();
        SystemTag dbSystemTagGroup = jdbcSession.findOne(SystemTag.class)
                .eq("deleted", false)
                .eq("group", true)
                .markBegin()
                .eq("id", id).or()
                .eq("name", systemTagGroup.getName()).or()
                .markEnd().exe();
        if (Objects.isNull(dbSystemTagGroup)) {
            systemTagGroup.setPid(Root.ROOT_ID);
            systemTagGroup.setGroup(true);
            systemTagGroup.setSort(System.currentTimeMillis());
            jdbcSession.insert(systemTagGroup);
        } else {
            throw new RuntimeException("标签组不能重复");
            //return Result.success("标签组不能重复");
           /* dbSystemTagGroup.setName(systemTagGroup.getName());
            jdbcSession.updateById(dbSystemTagGroup);
            systemTagGroup.setId(dbSystemTagGroup.getId());*/
        }
        List<SystemTag> systemTagList = systemTagGroup.getChildList();
        if (Objects.nonNull(systemTagList)) {
            for (SystemTag systemTag : systemTagList) {
                List<SystemTag> list = jdbcSession.findArray(SystemTag.class)
                        .eq("group", false)
                        .eq("deleted", false)
                        .eq("name", systemTag.getName()).exe();
                systemTag.setId(IDGenerate.uuid());
                systemTag.setPid(systemTagGroup.getId());
                systemTag.setGroup(false);
                systemTag.setCreateBy(Root.ROOT_ID);
                systemTag.setCreateName("系统");
            }
        }
        jdbcSession.insert(systemTagList);
        return Result.success();
    }

    /**
     * 更新标签组及标签
     *
     * @param systemTagGroup 系统标签对象
     * @return
     * @throws Exception
     */
    @Bean(copy = true)
    @ReqMapping("/group/update")
    public Object groupUpdate(SystemTag systemTagGroup) throws Exception {
        String id = systemTagGroup.getId();
        SystemTag dbSystemTagGroup = jdbcSession.findOne(SystemTag.class)
                .eq("deleted", false)
                .markBegin()
                .eq("id", id).or()
                .eq("name", systemTagGroup.getName()).or()
                .markEnd().exe();
        if (Objects.isNull(dbSystemTagGroup)) {
            return Result.success("0", "标签组不存在");
        }
        jdbcSession.updateById(systemTagGroup);


        //输入的标签集合
        List<SystemTag> systemTagList = systemTagGroup.getChildList();

        Map<String, SystemTag> mapping = systemTagList.stream().collect(Collectors.toMap(SystemTag::getId, Function.identity()));


        //数据库已存在的标签集合
        List<SystemTag> dbSystemTagList = jdbcSession.findArray(SystemTag.class)
                .eq("pid", dbSystemTagGroup.getId())
                .eq("group", false)
                .eq("deleted", false)
                .order("sort", "desc")
                .exe();


        //需要更新的标签集合
        List<SystemTag> updateSystemTagList = new ArrayList<>();

        //需要删除的标签集合
        List<SystemTag> deleteSystemTagList = new ArrayList<>();

        for (SystemTag dbSystemTag : dbSystemTagList) {
            String dbId = dbSystemTag.getId();
            if (mapping.containsKey(dbId)) {
                updateSystemTagList.add(mapping.get(dbId));
                systemTagList.remove(dbSystemTag);
            } else {
                deleteSystemTagList.add(dbSystemTag);
            }
        }

        //需要新增的标签集合
        List<SystemTag> addSystemTagList = new ArrayList<>(systemTagList);

        //增量新增标签
        if (Objects.nonEmpty(addSystemTagList)) {
            for (SystemTag systemTag : addSystemTagList) {
                systemTag.setId(IDGenerate.uuid());
                systemTag.setPid(dbSystemTagGroup.getId());
                systemTag.setGroup(false);
                systemTag.setCreateBy(Root.ROOT_ID);
                systemTag.setCreateName("系统");
            }
            jdbcSession.insert(addSystemTagList);
        }

        //增量更新标签
        if (Objects.nonEmpty(updateSystemTagList)) {
            jdbcSession.updateById(updateSystemTagList);
        }

        //增量删除标签
        if (Objects.nonEmpty(deleteSystemTagList)) {
            for (SystemTag systemTag : deleteSystemTagList) {
                systemTag.setDeleted(true);
            }
            jdbcSession.updateById(deleteSystemTagList);
        }
        return Result.success();
    }


    /**
     * 删除标签组及标签
     *
     * @param systemTagGroup 系统标签组对象
     * @return
     */
    @ReqMapping("/group/delete")
    public Object groupDelete(SystemTag systemTagGroup) {
        systemTagGroup.setDeleted(true);
        jdbcSession.updateById(systemTagGroup);
        if (systemTagGroup.isGroup()) {
            List<SystemTag> systemTagList = jdbcSession.findArray(SystemTag.class)
                    .eq("pid", systemTagGroup.getId())
                    .eq("group", false)
                    .eq("deleted", false)
                    .order("sort", "desc")
                    .exe();
            if (Objects.nonEmpty(systemTagList)) {
                for (SystemTag systemTag : systemTagList) {
                    systemTag.setDeleted(true);
                }
                jdbcSession.updateById(systemTagList);
            }
        }
        return Result.success();
    }


}
